package com.tianluo.tianluobookstore.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
@Slf4j
public class AliPayService {

    @Autowired
    private AlipayClient alipayClient;

    @Value("${alipay.notify-url}")
    private String notifyUrl;

    @Value("${alipay.return-url}")
    private String returnUrl;

    public String createOrder(String orderId, BigDecimal amount, String subject) throws AlipayApiException {
        // 创建支付请求
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(returnUrl); // 同步通知地址
        request.setNotifyUrl(notifyUrl); // 异步通知地址

        // 设置业务参数
        String bizContent = "{" +
                "    \"out_trade_no\":\"" + orderId + "\"," +
                "    \"total_amount\":\"" + amount + "\"," +
                "    \"subject\":\"" + subject + "\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"" +
                "  }";
        request.setBizContent(bizContent);

        // 调用支付宝接口
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if (response.isSuccess()) {
            return response.getBody(); // 返回支付页面的表单
        } else {
            throw new RuntimeException("支付宝支付请求失败：" + response.getMsg());
        }
    }
}
